package com.example.demo.controller;

import com.example.demo.dataobject.*;
import com.example.demo.repository.UserInfoRepository;
import com.example.demo.service.*;
import com.example.demo.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")  //解决跨域请求,但是无法做到对于session的共享，无法针对ajax请求，所以需要对参数值进行设置
public class UserController {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MedicineShorthandService medicineShorthandService;

    @Autowired
    private InsulinService insulinService;

    @Autowired
    private OralMedicineService oralMedicineService;

    @Autowired
    private UserService userService;

    @Autowired
    private BloodSugarService bloodSugarService;

    @Autowired
    private ComplicationService complicationService;

    @Autowired
    private TreatmentService treatmentService;

    @Autowired
    private HealthInfoService healthInfoService;

    @Autowired
    private FoodService foodService;

    @Autowired
    private BloodSugarRecordService bloodSugarRecordService;

    @Resource
    private HttpServletRequest httpServletRequest;

    private int type;




    @RequestMapping("/login")
    public String login(@RequestParam("telephone") String telephone,
                        @RequestParam("password") String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String encryptPassword = this.EncodeByMd5(password);
        boolean result = userInfoService.validateLogin(telephone, encryptPassword);
        if (result) {
            return "SUCCESS";
        }
        return "ERROR";
    }



    @RequestMapping("/register")
    public String register(@RequestParam("telephone") String telephone,
                           @RequestParam("password") String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String encryptPassword = this.EncodeByMd5(password);
        boolean result = userInfoService.register(telephone, encryptPassword);
        if (result) {
            return "SUCCESS";
        }
        return "ERROR";
    }


    public String EncodeByMd5(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();

        //加密字符串
        String encryptPassword = base64en.encode(md5.digest(password.getBytes("utf-8")));
        return encryptPassword;
    }




//    @RequestMapping("/saveComplication")
//    public String saveComplication(@RequestParam("telephone") String telephone,
//                                   @RequestParam("isDiabeticFootPathology") Integer isDiabeticFootPathology,
//                                   @RequestParam("isDiabeticRetinopathy") Integer isDiabeticRetinopathy,
//                                   @RequestParam("isDiabeticNephropathy") Integer isDiabeticNephropathy,
//                                   @RequestParam("isDiabeticCardiovascularDisease") Integer isDiabeticCardiovascularDisease,
//                                   @RequestParam("isDiabeticNeuropathy") Integer isDiabeticNeuropathy,
//                                   @RequestParam("isDiabeticSkinLesions") Integer isDiabeticSkinLesions,
//                                   @RequestParam("isHypertension") Integer isHypertension,
//                                   @RequestParam("isHyperlipidemia") Integer isHyperlipidemia,
//                                   @RequestParam("isOther") Integer isOther) {
//        UserInfo userInfo = userInfoRepository.findByTelephone(telephone);
//        Complication complication = new Complication(userInfo.getId(), isDiabeticFootPathology, isDiabeticRetinopathy, isDiabeticNephropathy, isDiabeticCardiovascularDisease, isDiabeticNeuropathy, isDiabeticSkinLesions, isHypertension, isHyperlipidemia, isOther);
//        Complication byTelephone = complicationService.findByTelephone(telephone);
//        // 这里是更新操作
//        if (byTelephone != null) {
//            complication.setId(byTelephone.getId());
//        }
//        boolean result = complicationService.save(complication);
//
//        if (result) {
//            return "SUCCESS";
//        }
//        return "ERROR";
//
//    }



//    @RequestMapping("/saveTreatment")
//    public String saveTreatment(@RequestParam("telephone") String telephone,
//                                @RequestParam("isDietControl") Integer isDietControl,
//                                @RequestParam("isExerciseTherapy") Integer isExerciseTherapy,
//                                @RequestParam("isOralMedication") Integer isOralMedication,
//                                @RequestParam("isInsulin") Integer isInsulin) {
//        UserInfo userInfo = userInfoRepository.findByTelephone(telephone);
//        Treatment treatment = new Treatment(userInfo.getId(), isDietControl, isExerciseTherapy, isOralMedication, isInsulin);
//        Treatment byTelephone = treatmentService.findByTelephone(telephone);
//        if (byTelephone != null) {
//            treatment.setId(byTelephone.getId());
//        }
//
//        boolean result = treatmentService.save(treatment);
//        if (result) {
//            return "SUCCESS";
//        }
//        return "ERROR";
//
//    }



//    @RequestMapping("/saveHealthInfo")
//    public String saveHealthInfo(@RequestParam("telephone") String telephone,
//                                 @RequestParam("identity") Integer identity,
//                                 @RequestParam("sex") Integer sex,
//                                 @RequestParam("birthYear") Integer birthYear,
//                                 @RequestParam("birthMonth") Integer birthMonth,
//                                 @RequestParam("weight") Integer weight,
//                                 @RequestParam("height") Integer height,
//                                 @RequestParam("laborIntensity") Integer laborIntensity,
//                                 @RequestParam("diabetesType") Integer diabetesType,
//                                 @RequestParam("diagnosisYear") Integer diagnosisYear,
//                                 @RequestParam("diagnosisMonth") Integer diagnosisMonth,
//                                 @RequestParam("treatment") Integer treatment,
//                                 @RequestParam("complication") Integer complication) {
//
//        UserInfo userInfo = userInfoRepository.findByTelephone(telephone);
//
//        HealthInfo byTelephone = healthInfoService.findByTelephone(telephone);
//        HealthInfo healthInfo = new HealthInfo(userInfo.getId(), identity, sex, birthYear, birthMonth, weight, height, laborIntensity, diabetesType, diagnosisYear, diagnosisMonth, treatment, complication);
//        if (byTelephone != null) {
//            healthInfo.setId(byTelephone.getId());
//        }
//        boolean result = healthInfoService.save(healthInfo);
//        if (result) {
//            return "SUCCESS";
//        }
//        return "ERROR";
//
//    }



//    @RequestMapping("/listHealthInfo")
//    public HealthInfo listHealthInfo(@RequestParam("telephone") String telephone) {
//        HealthInfo healthInfo = healthInfoService.findByTelephone(telephone);
//        if (healthInfo == null) {
//            return null;
//        } else {
//            return healthInfo;
//        }
//    }

//    @RequestMapping("/listFood")
//    public List<Food> listFood(@RequestParam("foodType") Integer foodType) {
//        List<Food> result = new ArrayList<>();
//        result = foodService.findByFoodTypeOrderByCarbonWater(foodType);
//        return result;
//    }
//
//    @RequestMapping("/listFoodDesc")
//    public List<Food> listFoodDesc(@RequestParam("foodType") Integer foodType) {
//        List<Food> result = new ArrayList<>();
//        result = foodService.findByFoodTypeOrderByCarbonWaterDesc(foodType);
//        return result;
//    }
//
//    @RequestMapping("/searchFood")
//    public List<Food> searchFoodByFoodName(@RequestParam("foodName") String foodName) {
//        List<Food> result = foodService.findByFoodNameLikeOrderByCarbonWater("%" + foodName + "%");
//        return result;
//    }

//    @RequestMapping("/saveBloodSugar")
//    public String saveBloodSugar(@RequestParam("bloodSugar") Double bloodSugar,
//                                 @RequestParam("telephone") String telephone,
//                                 @RequestParam("periodType") Integer periodType,
//                                 @RequestParam("date") Date date,
//                                 @RequestParam("remarks") String remarks) {
//        BloodSugar result = bloodSugarService.save(bloodSugar, telephone, periodType, date, remarks);
//        if (result == null) {
//            return "ERROR";
//        }
//        return "SUCCESS";
//    }


//    @RequestMapping("/saveBloodSugarRecord")
//    public String saveBloodSugarRecord(@RequestParam("bloodSugar") Double bloodSugar,
//                                       @RequestParam("telephone") String telephone,
//                                       @RequestParam("periodType") Integer periodType,
//                                       @RequestParam("date") Date date,
//                                       @RequestParam("recordTime") Timestamp recordTime,
//                                       @RequestParam("remarks") String remarks) {
//        BloodSugarRecord result = bloodSugarRecordService.save(bloodSugar, telephone, periodType, date, recordTime, remarks);
//        if (result == null) {
//            return "ERROR";
//        }
//        return "SUCCESS";
//    }


//    @RequestMapping("/listBloodSugarRecord")
//    public List<BloodSugarRecord> listBloodSugarRecord(@RequestParam("telephone") String telephone) {
//        List<BloodSugarRecord> result = bloodSugarRecordService.findByTelephone(telephone);
//        return result;
//    }


//    /**
//     * 请求路径和方法名改为searchSugarRecordInADay
//     *
//     * @param telephone
//     * @param date
//     * @return
//     */
//    @RequestMapping("/searchBloodSugarRecordInADay")
//    public List<BloodSugarRecord> searchBloodSugarRecordInADay(@RequestParam("telephone") String telephone,
//                                                               @RequestParam("date") Date date) {
//        List<BloodSugarRecord> result = bloodSugarRecordService.findByTelephoneAndDateOrderByRecordTime(telephone, date);
//        return result;
//    }

//    @RequestMapping("/deleteBloodSugarRecord")
//    public String deleteBloodSugarRecord(@RequestParam("id") Integer id) {
//        Boolean result = bloodSugarRecordService.delete(id);
//        if (result) {
//            return "SUCCESS";
//        }
//        return "ERROR";
//    }


//    @RequestMapping("/modifyBloodSugarRecord")
//    public String modifyBloodSugarRecord(@RequestParam("id") Integer id,
//                                         @RequestParam("bloodSugar") Double bloodSugar,
//                                         @RequestParam("telephone") String telephone,
//                                         @RequestParam("periodType") Integer periodType,
//                                         @RequestParam("date") Date date,
//                                         @RequestParam("recordTime") Timestamp recordTime,
//                                         @RequestParam("remarks") String remarks) {
//        BloodSugarRecord result = bloodSugarRecordService.saveModification(id, bloodSugar, telephone, periodType, date, recordTime, remarks);
//        if (result == null) {
//            return "ERROR";
//        }
//        return "SUCCESS";
//    }


//    @RequestMapping("/modifyMedicineShorthandRecord")
//    public String modifyMedicineShorthandRecord(@RequestParam("id") Integer id,
//                                                @RequestParam("telephone") String telephone,
//                                                @RequestParam("insulinName") String insulinName,
//                                                @RequestParam("insulinDose") Integer insulinDose,
//                                                @RequestParam("oralMedicineName") String oralMedicineName,
//                                                @RequestParam("oralMedicineDose") Integer oralMedicineDose,
//                                                @RequestParam("remarks") String remarks,
//                                                @RequestParam("recordTime") Timestamp recordTime) {
//        MedicineShorthand result = medicineShorthandService.saveModification(id, telephone, insulinName, insulinDose, oralMedicineName, oralMedicineDose, remarks, recordTime);
//        if (result == null) {
//            return "ERROR";
//        }
//        return "SUCCESS";
//
//    }
//
//
//    @RequestMapping("/listOralMedicine")
//    public List<OralMedicine> listOralMedicine() {
//        List<OralMedicine> result = oralMedicineService.findAll();
//        return result;
//    }
//
//    @RequestMapping("/searchOralMedicine")
//    public List<OralMedicine> searchOralMedicine(@RequestParam("name") String name) {
//        List<OralMedicine> result = oralMedicineService.findByNameLikeOrderById("%" + name + "%");
//        return result;
//    }
//
//    @RequestMapping("/listInsulin")
//    public List<Insulin> listInsulin() {
//        List<Insulin> result = insulinService.findAll();
//        return result;
//    }
//
//    @RequestMapping("/searchInsulin")
//    public List<Insulin> searchInsulin(@RequestParam("name") String name) {
//        List<Insulin> result = insulinService.findByNameLikeOrderById("%" + name + "%");
//        return result;
//    }
//
//    @RequestMapping("/saveMedicineShorthand")
//    public String saveMedicineShorthand(@RequestParam("telephone") String telephone,
//                                        @RequestParam("insulinName") String insulinName,
//                                        @RequestParam("insulinDose") Integer insulinDose,
//                                        @RequestParam("oralMedicineName") String oralMedicineName,
//                                        @RequestParam("oralMedicineDose") Integer oralMedicineDose,
//                                        @RequestParam("remarks") String remarks,
//                                        @RequestParam("recordTime") Timestamp recordTime) {
//        MedicineShorthand result = medicineShorthandService.save(telephone, insulinName, insulinDose, oralMedicineName, oralMedicineDose, remarks, recordTime);
//        if (result == null) {
//            return "ERROR";
//        }
//        return "SUCCESS";
//    }


//    @RequestMapping("/listMedicineShorthand")
//    public List<MedicineShorthand> listMedicineShorthand(@RequestParam("telephone") String telephone) {
//        List<MedicineShorthand> result = medicineShorthandService.findByTelephoneOrderByRecordTimeDesc(telephone);
//        return result;
//    }
//
//    @RequestMapping("/findLastSugarRecord")
//    public BloodSugarRecord findLastSugarRecord(@RequestParam("telephone") String telephone) {
//        BloodSugarRecord result = bloodSugarRecordService.findLastSugarRecord(telephone);
//        return result;
//    }


    @RequestMapping("/modifyPassword")
    public String modifyPassword(@RequestParam("telephone") String telephone,
                                 @RequestParam("originalPassword") String originalPassword,
                                 @RequestParam("currentPassword") String currentPassword) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        originalPassword = this.EncodeByMd5(originalPassword);
        currentPassword = this.EncodeByMd5(currentPassword);
        boolean result = userInfoService.modifyPassword(telephone, originalPassword, currentPassword);
        if (result) {
            return "SUCCESS";
        }
        return "ERROR";
    }


    @RequestMapping("/modifyNickname")
    public String modifyNickname(@RequestParam("telephone") String telephone,
                                 @RequestParam("nickname") String nickname) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        boolean result = userInfoService.modifyNickname(telephone, nickname);
        if (result) {
            return "SUCCESS";
        }
        return "ERROR";
    }

    @RequestMapping("/modifyTelephone")
    public String modifyTelephone(@RequestParam("originalTelephone") String originalTelephone,
                                  @RequestParam("password") String password,
                                  @RequestParam("currentTelephone") String currentTelephone) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        password = this.EncodeByMd5(password);
        boolean result = userInfoService.modifyTelephone(originalTelephone, password, currentTelephone);
        if (result) {
            return "SUCCESS";
        }
        return "ERROR";
    }

    @RequestMapping("/findUserInfoByTelephone")
    public UserInfo findUserInfoByTelephone(@RequestParam("telephone") String telephone) {
        UserInfo userInfo = userInfoService.findByTelephone(telephone);
        return userInfo;
    }

    @RequestMapping("/modifyProfilePicture")
    public String modifyProfilePicture(@RequestParam("telephone") String telephone,
                                       @RequestParam("pictureId") Integer pictureId) {

        boolean result = userInfoService.modifyProfilePicture(telephone, pictureId);
        if (result) {
            return "SUCCESS";
        }
        return "ERROR";
    }

//    @RequestMapping("/findHealthInfo")
//    public HealthInfo findHealthInfo(@RequestParam("telephone") String telephone) {
//        HealthInfo result = healthInfoService.findByTelephone(telephone);
//        if (result == null) {
//            return null;
//        }
//        return result;
//
//    }

//    @RequestMapping("/findBloodSugarRecordInAWeek")
//    public List<BloodSugarRecord> findBloodSugarRecordInAWeek(@RequestParam("telephone") String telephone,
//                                                              @RequestParam("date") Date date) {
//        List<BloodSugarRecord> result = bloodSugarRecordService.findByUserIdAndDateInAWeek(telephone, date);
//        return result;
//    }
//
//    @RequestMapping("/findBloodSugarRecordInAPeriod")
//    public List<BloodSugarRecord> findBloodSugarRecordInAPeriod(@RequestParam("telephone") String telephone,
//                                                                @RequestParam("date") Date date) {
//        List<BloodSugarRecord> result = bloodSugarRecordService.findByUserIdAndDateInAPeriod(telephone, date);
//        return result;
//    }


}
